package com.tudouji.project.farepay.service.impl;

import com.tudouji.common.enums.WlinfoPayStatusEnum;
import com.tudouji.common.utils.SecurityUtils;
import com.tudouji.framework.web.domain.AjaxResult;
import com.tudouji.project.farepay.domain.FarepayApply;
import com.tudouji.project.farepay.domain.FarepayDetails;
import com.tudouji.project.farepay.mapper.FarepayApplyMapper;
import com.tudouji.project.farepay.mapper.FarepayDetailsMapper;
import com.tudouji.project.farepay.service.IFarepayDetailsService;
import com.tudouji.project.system.domain.SysUser;
import com.tudouji.project.system.domain.Tuser;
import com.tudouji.project.system.mapper.TuserMapper;
import com.tudouji.project.wlinfo.domain.Wlinfo;
import com.tudouji.project.wlinfo.mapper.WlinfoMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 物流运费付款申请明细Service业务层处理
 *
 * @author tudouji
 * @date 2021-10-27
 */
@Service
public class FarepayDetailsServiceImpl implements IFarepayDetailsService
{
    @Autowired
    private FarepayDetailsMapper farepayDetailsMapper;
    @Autowired
    private FarepayApplyMapper farepayApplyMapper;
    @Autowired
    private WlinfoMapper wlinfoMapper;
    @Autowired
    private TuserMapper tuserMapper;

    /**
     * 查询物流运费付款申请明细
     *
     * @param guid 物流运费付款申请明细ID
     * @return 物流运费付款申请明细
     */
    @Override
    public FarepayDetails selectFarepayDetailsById(String guid)
    {
        return farepayDetailsMapper.selectFarepayDetailsById(guid);
    }

    /**
     * 查询物流运费付款申请明细列表
     *
     * @param farepayDetails 物流运费付款申请明细
     * @return 物流运费付款申请明细
     */
    @Override
    public List<FarepayDetails> selectFarepayDetailsList(FarepayDetails farepayDetails)
    {
        return farepayDetailsMapper.selectFarepayDetailsList(farepayDetails);
    }

    /**
     * 新增物流运费付款申请明细
     *
     * @return 结果
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult insertFarepayDetails(FarepayDetails details)
    {
        try{
            String phone = SecurityUtils.getLoginUser().getUser().getPhonenumber();
            Tuser tuser = tuserMapper.selectTuserByName(phone);
            if (StringUtils.isNotBlank(details.getWlinfoids())) {
                String[] wlinfoids = details.getWlinfoids().split(",");

                details.setWls(wlinfoids);
            }
            List<Wlinfo> items = wlinfoMapper.selectWlinfoByIds(details);
            for (int i = 0; i < items.size(); i++) {
                FarepayApply apply = farepayApplyMapper.selectFarepayApplyById(details.getFarepayGuid());
                if (apply.getStatus() != -1){
                    return AjaxResult.error("非草稿状态不能添加");
                }
                Wlinfo wl = items.get(i);
                //付款申请主表非删除状态的明细中是否包含此物流编号
                Integer count = farepayApplyMapper.checkNotInDetail(wl.getGuid());
                if (count > 0){
                    return  AjaxResult.error("编号：" + wl.getCode() + "已申请");
                }
                details.setWlinfoGuid(wl.getGuid());
                details.setWlinfoCode(wl.getCode());
                details.setAmount(wl.getAmount());
                details.setCreatetime(new Date());
                details.setOperatorid(tuser.getGuid());
                details.setOperator(tuser.getRealname());
                apply.setApplyAmount(
                        (apply.getApplyAmount() == null ? BigDecimal.ZERO : apply.getApplyAmount()).add(details.getAmount()));
                apply.setAmount(
                        (apply.getAmount() == null ? BigDecimal.ZERO : apply.getAmount()).add(details.getAmount()));
                apply.setTotalamount(
                        (apply.getTotalamount() == null ? BigDecimal.ZERO : apply.getTotalamount()).add(details.getAmount()));
                farepayApplyMapper.updateFarepayApply(apply);

                Wlinfo wlUp = new Wlinfo();
                wlUp.setGuid(wl.getGuid());
                wlUp.setPaystatus(WlinfoPayStatusEnum.PAYING.getCode());
                wlinfoMapper.updateWlinfo(wlUp);
                this.farepayDetailsMapper.insertFarepayDetails(details);
            }
            return AjaxResult.success();
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error();
        }
    }

    /**
     * 修改物流运费付款申请明细
     *
     * @param farepayDetails 物流运费付款申请明细
     * @return 结果
     */
    @Override
    public int updateFarepayDetails(FarepayDetails farepayDetails)
    {
        return farepayDetailsMapper.updateFarepayDetails(farepayDetails);
    }

    /**
     * 批量删除物流运费付款申请明细
     *
     * @param guids 需要删除的物流运费付款申请明细ID
     * @return 结果
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult deleteFarepayDetailsByIds(String[] guids)
    {
        try{
            for (int i = 0; i < guids.length; i++) {
                String detailsguid = guids[i];
                FarepayDetails details = farepayDetailsMapper.selectFarepayDetailsById(detailsguid);
                //修改主表的amount
                FarepayApply apply = farepayApplyMapper.selectFarepayApplyById(details.getFarepayGuid());
                if (apply.getStatus() != -1){
                    return AjaxResult.error("非草稿状态不能删除");
                }
                apply.setApplyAmount(
                        (apply.getApplyAmount() == null ? BigDecimal.ZERO : apply.getApplyAmount()).subtract(details.getAmount()));
                apply.setAmount(
                        (apply.getAmount() == null ? BigDecimal.ZERO : apply.getAmount()).subtract(details.getAmount()));
                apply.setTotalamount(
                        (apply.getTotalamount() == null ? BigDecimal.ZERO : apply.getTotalamount()).subtract(details.getAmount()));
                farepayApplyMapper.updateFarepayApply(apply);

                Wlinfo wlinfo = new Wlinfo();
                wlinfo.setGuid(details.getWlinfoGuid());
                wlinfo.setPaystatus(WlinfoPayStatusEnum.DPAYING.getCode());
                wlinfoMapper.updateWlinfo(wlinfo);
                this.farepayDetailsMapper.deleteFarepayDetailsById(detailsguid);
            }
            return AjaxResult.success();
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error();
        }
    }

    /**
     * 删除物流运费付款申请明细信息
     *
     * @param guid 物流运费付款申请明细ID
     * @return 结果
     */
    @Override
    public int deleteFarepayDetailsById(String guid)
    {
        return farepayDetailsMapper.deleteFarepayDetailsById(guid);
    }

	@Override
	public List<FarepayDetails> selectFarepayList(String wlinfoId) {
		//Auto-generated method stub
		return farepayDetailsMapper.selectFarepayList(wlinfoId);
	}

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult delItem(String itemGuids) {
        String[] ids = itemGuids.split( "," );
        for (int i = 0; i < ids.length; i++) {
            String id = ids[i];
            FarepayDetails farepayDetails = farepayDetailsMapper.selectFarepayDetailsById(id);
            //修改主表的amount
            FarepayApply apply = farepayApplyMapper.selectFarepayApplyById(farepayDetails.getFarepayGuid());
            apply.setApplyAmount(apply.getApplyAmount().add(farepayDetails.getAmount()));
            farepayApplyMapper.updateFarepayApply(apply);

            Wlinfo wlinfo = new Wlinfo();
            wlinfo.setGuid(farepayDetails.getWlinfoGuid());
            wlinfo.setPaystatus(WlinfoPayStatusEnum.START.getCode());
            wlinfoMapper.updateWlinfo(wlinfo);
            this.farepayDetailsMapper.deleteFarepayDetailsById(id);
        }
        return AjaxResult.success();
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult addItem(List<FarepayDetails> items) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();

        for (int i = 0; i < items.size(); i++) {
            FarepayDetails details = items.get(i);
            details.setCreatetime(new Date());
            details.setOperatorid(sysUser.getTuserId());
            //修改主表的amount
            FarepayApply apply = farepayApplyMapper.selectFarepayApplyById(details.getFarepayGuid());
            apply.setApplyAmount(apply.getApplyAmount().add(details.getAmount()));
            farepayApplyMapper.updateFarepayApply(apply);

            Wlinfo wlinfo = new Wlinfo();
            wlinfo.setGuid(details.getWlinfoGuid());
            wlinfo.setPaystatus(WlinfoPayStatusEnum.DPAYING.getCode());
            wlinfoMapper.updateWlinfo(wlinfo);
            this.farepayDetailsMapper.insertFarepayDetails(details);
        }
        return AjaxResult.success();
    }
}
